const {getData} = require("../../DAO/getData");
const connection = require('../../db/sql')
const objectArrayDeweight = require("../../utils/object-array-deweight");

// 获取角色数据
async function selectRole(params, res) {
    let {role_description} = params
    // 查询权限和角色信息
    console.log(role_description, '少数')
    let sql = ''
    //如果角色表述存在,则查询指定表述的的角色信息(角色英文名,对应权限)
    if (role_description) {
        sql = `SELECT p.rank_id, permission_name, r.role_id, role_name, role_description
FROM permissions p
LEFT JOIN role_permission rp ON p.rank_id = rp.rank_id
LEFT JOIN roles r ON rp.role_id = r.role_id where role_description like'%${role_description}%'`;
    } else {//如果没有,则查询所有角色信息
        sql = `SELECT p.rank_id, permission_name, r.role_id, role_name, role_description
FROM permissions p
LEFT JOIN role_permission rp ON p.rank_id = rp.rank_id
LEFT JOIN roles r ON rp.role_id = r.role_id`;
    }

// 执行查询
    connection.query(sql, (err, result) => {
        if (err) {
            console.log(err);
            return;
        }
        // 处理数据
        let permissions = [];
        let roles = [];
        // console.log(result,'撒谎电动')
        result.forEach(item => {
            if (item.rank_id > 5) {//大于5表示属于真正的权限,小于5的相当于只是一部分真正的权限所属的分类,
                let permissionInfo = {
                        // permission_id: item.permission_id,
                        permission_name: item.permission_name,
                        rank_id: item.rank_id
                    }

                ;
                // 将权限信息存入数组
                permissions.push(permissionInfo);
                // 将角色信息存入数组
                let roleInfo = {
                    role_id: item.role_id,
                    role_name: item.role_name,
                    role_description: item.role_description,
                    permissions: []
                };
                // 如果角色信息在数组中不存在，则添加
                if (roles.findIndex(role => role.role_id === item.role_id) === -1) {
                    roles.push(roleInfo);
                }
                // 将权限信息添加到对应的角色中
                roles.forEach(role => {
                    if (role.role_id === item.role_id) {
                        role.permissions.push(item.rank_id);
                    }
                });
            }
        });
        // 返回数据
        // let crs = objectArrayDeweight(permissions)
        console.log(roles, '岁欧艾斯')//roles,'时代欧珀',
        return res.json({
            success: true,
            data: {
                permissions: permissions,
                roles: roles
            }
        });
    });
}

module.exports = selectRole

